//
//  ViewController.m
//  PywSdkDemo
//
//  Created by Jade on 16/11/12.
//  Copyright © 2016年 Jade. All rights reserved.
//

#import "ViewController.h"
#import "ZXPAutoLayout.h"
#import "SelectedFunctionView.h"
#import "AppDelegate.h"
#import <objc/message.h>
#import "SVProgressHUD.h"
#import <PywCommonSDK/PywCommonSDK.h>

@interface ViewController ()<PywPasswordViewDelegate>
@property (nonatomic, strong) UIButton              *configBtn;     // 初始化
@property (nonatomic, strong) UIView                *auditFlagView; // 审核标识View
@property (nonatomic, strong) UITextField           *gameKeyText;   // GameKey输入框
@property (nonatomic, strong) UITextField           *channelText;   // channel输入框

@property (nonatomic, strong) UIButton              *loginBtn;      // 进入游戏
@property (nonatomic, strong) SelectedFunctionView  *selectedView;  // 选择功能

@property (nonatomic, copy) NSString *payType;  // 充值类型，1为固定支付，2为任意支付
@property (nonatomic, copy) NSString *cpID;     // 商品ID
@property (nonatomic, copy) NSString *price;    // 金额
@property (nonatomic, copy) NSString *rolename; // 游戏角色
@property (nonatomic, copy) NSString *service;  // 游戏区服
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self bgName]]];
    [self.view addSubview:bg];
    [bg zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
        layout.topSpace(0).leftSpace(0).bottomSpace(0).rightSpace(0);
    }];
    
    [self addNotification];
    [self configConstraints];
}
///  根据设备类型，以及app设置的屏幕支持方向。设置当前控制器的背景图片资源文件名
- (NSString *)bgName
{
    __block NSString *bgImgName = @"";
    
    // 获取info.plist文件配置
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:bundlePath];
//    NSLog(@"dict===%@",dict);
    
    // 获取iPhone与iPad屏幕方向的Key
    // ipad : UISupportedInterfaceOrientations~ipad
    // iphone : UISupportedInterfaceOrientations
    NSString *iphoneKey = @"UISupportedInterfaceOrientations";
    NSString *iPadKey = @"UISupportedInterfaceOrientations~ipad";
    
    // 获取设备类别
    NSString *deviceName = [UIDevice currentDevice].model;
//    NSLog(@"设备: %@",deviceName);
    if ([deviceName isEqualToString:@"iPhone"]) {
        NSArray *iphongOrientationArr = [dict objectForKey:iphoneKey];
        [iphongOrientationArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 如果数组中，包含UIInterfaceOrientationLandscapeLeft或UIInterfaceOrientationLandscapeRight，横屏
            if ([obj isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]
                || [obj isEqualToString:@"UIInterfaceOrientationLandscapeRight"]) {
//                NSLog(@"支持横屏！");
                bgImgName = @"horizontal_bg";
            }
            // 如果数组中，包含UIInterfaceOrientationPortrait，竖屏
            else if ([obj isEqualToString:@"UIInterfaceOrientationPortrait"]){
//                NSLog(@"支持竖屏！");
                bgImgName = @"vertical_bg";
            }
            // 否则，支持横竖屏
            else{
//                NSLog(@"支持横竖屏！");
                bgImgName = @"vertical_bg";
            }
            
        }];
        
    }else if ([deviceName isEqualToString:@"iPad"]){
        
        NSArray *ipadOrientationArr = [dict objectForKey:iPadKey];
        [ipadOrientationArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 如果数组中，包含UIInterfaceOrientationLandscapeLeft或UIInterfaceOrientationLandscapeRight，横屏
            if ([obj isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]
                || [obj isEqualToString:@"UIInterfaceOrientationLandscapeRight"]) {
//                NSLog(@"支持横屏！");
                bgImgName = @"horizontal_bg";
            }
            // 如果数组中，包含UIInterfaceOrientationPortrait，竖屏
            else if ([obj isEqualToString:@"UIInterfaceOrientationPortrait"]){
//                NSLog(@"支持竖屏！");
                bgImgName = @"vertical_bg";
            }
            // 否则，支持横竖屏
            else{
//                NSLog(@"支持横竖屏！");
                bgImgName = @"vertical_bg";
            }
            
        }];
    }
    return bgImgName;
}

- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(inited:)
                                                 name:kCP_XpCommon_InitNotification    // 初始化完成
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(logined:)
                                                 name:kCP_XpCommon_LoginNotification   // 登录完成
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(logouted:)
                                                 name:kCP_XpCommon_LogoutNotification  // 注销完成
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payed:)
                                                 name:kCP_XpCommon_PayNotification     // 支付完成
                                               object:nil];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - prepareUI
- (void)configConstraints{
    __weak typeof(self) wSelf = self;
    [self.view addSubview:self.configBtn];
    self.configBtn.hidden = NO;
    [self.configBtn zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
        layout.widthValue(200).heightValue(40);
        layout.bottomSpace(40);
        layout.xCenterByView(wSelf.loginBtn.superview,0);
    }];
//    [self.view addSubview:self.auditFlagView];
//    self.auditFlagView.hidden = NO;
//    [self.auditFlagView zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
//        layout.widthValue(300).heightValue(80);
//        layout.xCenterByView(wSelf.auditFlagView.superview,0);
//        layout.topSpace(40);
//    }];
}
- (void)prepareUI{
    
    [self.view addSubview:self.loginBtn];
    __weak typeof(self) wSelf = self;
    [wSelf.loginBtn zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
        layout.widthValue(200).heightValue(40);
        layout.bottomSpace(40);
        layout.xCenterByView(wSelf.loginBtn.superview,0);
    }];
    
    [self.view addSubview:self.selectedView];
    [wSelf.selectedView zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
        layout.topSpace(10);
        layout.leftSpace(10);
        layout.rightSpace(10);
        layout.heightValue(280);
    }];
    
    self.loginBtn.hidden = NO;
    self.selectedView.hidden = YES;
}
#pragma mark - Action
// 初始化
- (void)configAction:(UIButton *)btn{
    [self.view endEditing:YES];
    [PywCommonSDKApi commonSdk_InitWithGamekey:@"c05d2487"];
//    [PywCommonSDKApi commonSdk_InitWithGamekey:@"e07cf6c9"];
    
//    if (self.gameKeyText.text.length == 0 && self.channelText.text.length == 0) {
//        [SVProgressHUD showErrorWithStatus:@"Gamekey和Channel不能为空！"];
//        return;
//    }
    
    // 初始化聚合接口
//    [PywCommonSDKApi commonSdk_InitWithGamekey:self.gameKeyText.text
//                                       channel:self.channelText.text];
}
// 进入游戏
- (void)loginAction:(UIButton *)btn{
    [PywCommonSDKApi commonSdk_ShowLogin];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
#pragma mark - PywPasswordViewDelegate
- (void)selectedFunctionView:(SelectedFunctionView *)view selectedButton:(UIButton *)btn{
    NSLog(@"%ld",(long)btn.tag);
    switch (btn.tag) {
        case 100: // 游戏充值
        {
            NSString *payType = [self.selectedView.payType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            NSString *cpID = [self.selectedView.cpID stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            NSString *cpPrice = [self.selectedView.price stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            NSString *rolename = [self.selectedView.rolename stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            NSString *service = [self.selectedView.service stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            
            if (payType.length == 0) { // 当“支付类型”未设置时，提示设置
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                message:@"请设置支付类型！支付类型有：\n  1：代表“固定支付”；\n  2：代表“任意支付”。"
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }else if ([payType isEqualToString:@"1"]){ // 固定支付，所有设置都不能为空
                if (cpID.length > 0 && cpPrice.length > 0
                    && rolename.length > 0 && service.length > 0) {
                    
                    self.payType = payType;
                    self.cpID = cpID;
                    self.price = cpPrice;
                    self.rolename = rolename;
                    self.service = service;
                    [self cpPay];
                }else{
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                    message:@"固定支付时，商品ID、商品价格、游戏角色和游戏区服均不能为空！"
                                                                   delegate:self
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
            }else if ([payType isEqualToString:@"2"]){ // 任意支付，商品ID可不传
                if (cpPrice.length > 0 && rolename.length > 0 && service.length > 0) {
                    
                    self.payType = payType;
                    self.cpID = cpID;
                    self.price = cpPrice;
                    self.rolename = rolename;
                    self.service = service;
                    [self cpPay];
                }else{
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                    message:@"任意支付时，商品价格、游戏角色和游戏区服均不能为空！"
                                                                   delegate:self
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
            }else{ // 无对应支付方式，提示设置出错
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                message:@"支付类型设置有误！支付类型仅有：\n  1：代表“固定支付”；\n  2：代表“任意支付”。"
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            
        }
            break;
        case 200: // 用户中心
        {
            [PywCommonSDKApi commonSdk_ShowUserCenter];
        }
            break;
        case 300: // 注销用户
        {
            [PywCommonSDKApi commonSdk_ShowLogout];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - pay
/**
 *  支付 信息
 */
- (void)cpPay {
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString = [dateformatter stringFromDate:date];
    
    NSString *random = [NSString stringWithFormat:@"%u",arc4random()%100];
    locationString = [locationString stringByAppendingString:random];
    NSString *orderId = [NSString stringWithFormat:@"order%@",locationString];
    
    NSString *gameBi = [NSString stringWithFormat:@"%d钻石",[self.price intValue] * 10];// 商品描述，显示在订单上面
    int amount = 6;     // 固定支付金额，固定支付由“朋友玩”后台配好商品价格，必须跟cpprodid一一对应
    if ([self.price intValue] > 0) {
        amount = [self.price intValue];
    }
    // 注意：支付金额不能带小数
    NSString *oriprice = [NSString stringWithFormat:@"%d", amount];
    
    NSString * cpprodid = @"";
    if (self.cpID.length > 0) {
        cpprodid = self.cpID;    // 商品id  固定支付的时候必传
    }
    
    NSString *gameOrderID = orderId; // 游戏订单ID，CP自定义生成
    NSString *payType = self.payType;// 充值类型，1为定额充值，2为任意充值【备注：火速SDK只能传1】
    
//    NSDictionary *cpprams = @{kcpCom_GameChannel:@"渠道编号",// channel：渠道号，保留值
//                              kcpCom_GamePartyInfo:@"朋友玩",// 游戏区服务编号，保留值
//                              };
    
    NSDictionary *roleInfo = @{keyCom_GameRoleId:@"123",// 游戏角色ID，必传
                               keyCom_GameRoleName:self.rolename,// 游戏角色名，必传
                               keyCom_GameRoleLevel:@"10",// 游戏角色等级,必传
                               keyCom_GameServiceId:@"115",// 区服ID，必传
                               keyCom_GameServiceName:self.service,// 区服名，必传
                               };
    
    NSDictionary *payInfo = @{keyCom_GoodsDesc:gameBi,// 商品描述，显示在订单上面
                              keyCom_GoodsPrice:oriprice,// 固定支付金额
                              keyCom_GoodsId:cpprodid,// 商品id，必传
                              keyCom_GameOrderId:gameOrderID,// 游戏订单号
                              keyCom_PayType:payType,// 支付类型 1为定额，0为任意
                              keyCom_GameRoleInfo: roleInfo,// 游戏角色信息,必传
                              keyCom_CustomParams:@"pararmssss",// 存储商品信息的字典,CP自定义参数
                              };
    /**
     *  调用SDK的 固定支付
     */
    [PywCommonSDKApi commonSdk_StartPay:payInfo];
}
#pragma mark - notification
/**
 * 初始化完成
 */
- (void)inited:(NSNotification *)notification {
    NSDictionary *dict = [notification userInfo];
    NSNumber *result = [dict objectForKey:@"result"];
    NSString *info = [dict objectForKey:@"info"];
    NSLog(@"dict = %@ 初始化状态 - %d | %@",dict.description, [result intValue],info);
    
    [self prepareUI];
    if ([result intValue] == 1) { // 初始化失败
        self.configBtn.hidden = NO;
        self.loginBtn.hidden = YES;
//        self.auditFlagView.hidden = NO;
        self.loginBtn.userInteractionEnabled = NO;
    } else {
//        self.auditFlagView.hidden = YES;
        self.configBtn.hidden = YES;
        self.loginBtn.hidden = NO;
        self.loginBtn.userInteractionEnabled = YES;
    }
    
    NSString *result_str = [NSString stringWithFormat:@"初始化:\n--%@--状态码:%d--",info,[result intValue]];
    [SVProgressHUD showInfoWithStatus:result_str];
}

/**
 * 登录完成
 */
- (void)logined:(NSNotification *)notification {
    NSDictionary *dict = [notification userInfo];
    NSNumber *result = [dict objectForKey:@"result"];
    NSString *info = [dict objectForKey:@"info"];
    NSLog(@"dict = %@ 登录状态 - %d | %@",dict.description, [result intValue],info);
    
    /**
     *  判断是否已登录，登录成功后显示 悬浮按钮
     */
    if (result.intValue == 0) {
        self.configBtn.hidden = YES;
        self.loginBtn.hidden = YES;
        self.selectedView.hidden = NO;
        [PywCommonSDKApi commonSdk_ShowOrHideFloatView:YES];
        
        // 设置游戏角色信息
        NSDictionary *roleInfo = @{keyCom_GameRoleId:@"123",            // 游戏角色ID，必传
                                   keyCom_GameRoleName:@"iOS测试账号",   // 游戏角色名，必传
                                   keyCom_GameRoleLevel:@"10",          // 游戏角色等级,必传
                                   keyCom_GameServiceId:@"115",         // 区服ID，必传
                                   keyCom_GameServiceName:@"测试115服",  // 区服名，必传
                                   keyCom_GameDataType:@"createRole",
                                   };
        [PywCommonSDKApi commonSdk_SetPlayerInfo:roleInfo];
    }
    
    NSString *result_str = [NSString stringWithFormat:@"登录:\n--%@--状态码:%d--",info,[result intValue]];
    [SVProgressHUD showInfoWithStatus:result_str];
}

/**
 *  注销完成
 */
- (void)logouted:(NSNotification *)notification {
    NSDictionary *dict = [notification userInfo];
    NSNumber *result = [dict objectForKey:@"result"];
    NSString *info = [dict objectForKey:@"info"];
    NSLog(@"dict = %@ 注销状态 - %d | %@",dict.description,[result intValue],info);
    
    [self prepareUI];
    
    NSString *result_str = [NSString stringWithFormat:@"注销:\n--%@--状态码:%d--",info,[result intValue]];
    [SVProgressHUD showInfoWithStatus:result_str];
}

- (void)payed:(NSNotification *)notification {
    NSDictionary *dict = [notification userInfo];
    NSNumber *result = [dict objectForKey:@"result"];
    NSString *info = [dict objectForKey:@"info"];
    NSLog(@"dict = %@ 支付状态 - %d | %@",dict.description, [result intValue],info);
    
    NSString *result_str = [NSString stringWithFormat:@"支付:\n--%@--状态码:%d--",info,[result intValue]];
    [SVProgressHUD showInfoWithStatus:result_str];
}

#pragma mark - Lazy
- (UIButton *)configBtn{
    if (!_configBtn) {
        _configBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _configBtn.backgroundColor = [UIColor orangeColor];
        _configBtn.layer.cornerRadius = 5;
        [_configBtn setTitle:@"初始化" forState:UIControlStateNormal];
        [_configBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        [_configBtn addTarget:self action:@selector(configAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _configBtn;
}
- (UIView *)auditFlagView{
    if (!_auditFlagView) {
        _auditFlagView = [UIView new];
        _auditFlagView.backgroundColor = [UIColor whiteColor];
        _auditFlagView.layer.cornerRadius = 5;
        _auditFlagView.layer.masksToBounds = YES;
        _auditFlagView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _auditFlagView.layer.borderWidth = 1;
        
        // 游戏参数
        UILabel *gameKeyLabel = [UILabel new];
        gameKeyLabel.backgroundColor = [UIColor clearColor];
        gameKeyLabel.font = [UIFont systemFontOfSize:14];
        gameKeyLabel.textAlignment = NSTextAlignmentCenter;
        gameKeyLabel.textColor = [UIColor blackColor];
        gameKeyLabel.text = @"Gamekey：";
        [_auditFlagView addSubview:gameKeyLabel];
        
        [gameKeyLabel zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
            layout.topSpace(0).leftSpace(0);
            layout.widthValue(80).heightValue(40);
        }];
        
        UITextField *gameKeyText = [UITextField new];
        gameKeyText.backgroundColor = [UIColor clearColor];
        gameKeyText.textAlignment = NSTextAlignmentLeft;
        gameKeyText.font = [UIFont systemFontOfSize:14];
        gameKeyText.autocorrectionType = UITextAutocorrectionTypeNo;
        gameKeyText.autocapitalizationType = UITextAutocapitalizationTypeNone;
        gameKeyText.clearButtonMode = UITextFieldViewModeWhileEditing;
        gameKeyText.textColor = [UIColor blackColor];
        gameKeyText.placeholder = @"请输入Gamekey";
        gameKeyText.text = @"c711934f"; // 小朋：c711934f   // 火速：53c8a121
        self.gameKeyText = gameKeyText;
        [_auditFlagView addSubview:gameKeyText];
        
        [gameKeyText zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
            layout.topSpace(0).rightSpace(0);
            layout.leftSpaceByView(gameKeyLabel,0);
            layout.heightValue(40);
        }];
        
        // 水平分隔线
        UIView *h_line = [[UIView alloc] init];
        h_line.backgroundColor = [UIColor lightGrayColor];
        [_auditFlagView addSubview:h_line];
        [h_line zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
            layout.topSpace(39.5).leftSpace(0).rightSpace(0);
            layout.heightValue(1);
        }];
        
        // 渠道参数
        UILabel *channelLabel = [UILabel new];
        channelLabel.backgroundColor = [UIColor clearColor];
        channelLabel.font = [UIFont systemFontOfSize:14];
        channelLabel.textAlignment = NSTextAlignmentCenter;
        channelLabel.textColor = [UIColor blackColor];
        channelLabel.text = @"Channel ：";
        [_auditFlagView addSubview:channelLabel];
        
        [channelLabel zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
            layout.bottomSpace(0).leftSpace(0);
            layout.widthValue(80).heightValue(40);
        }];
        
        UITextField *channelText = [UITextField new];
        channelText.backgroundColor = [UIColor clearColor];
        channelText.textAlignment = NSTextAlignmentLeft;
        channelText.font = [UIFont systemFontOfSize:14];
        channelText.autocorrectionType = UITextAutocorrectionTypeNo;
        channelText.autocapitalizationType = UITextAutocapitalizationTypeNone;
        channelText.clearButtonMode = UITextFieldViewModeWhileEditing;
        channelText.textColor = [UIColor blackColor];
        channelText.placeholder = @"请输入channel";
        channelText.text = @"21"; // 21：朋友玩（优趣）  // 30：火速
        self.channelText = channelText;
        [_auditFlagView addSubview:channelText];
        
        [channelText zxp_addConstraints:^(ZXPAutoLayoutMaker *layout) {
            layout.bottomSpace(0).rightSpace(0);
            layout.leftSpaceByView(channelLabel,0);
            layout.heightValue(40);
        }];
    }
    return _auditFlagView;
}
- (UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.backgroundColor = [UIColor orangeColor];
        _loginBtn.layer.cornerRadius = 5;
        [_loginBtn setTitle:@"进入游戏" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        [_loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}
- (SelectedFunctionView *)selectedView{
    if (!_selectedView) {
        _selectedView = [[SelectedFunctionView alloc] initWithDelegate:self];
    }
    return _selectedView;
}
@end
